const User = require('../model/user.model')

const createUser = async (username, password) => {
  const result = await User.create({
    username,
    password,
    isAdmin: username === 'zhengyimeng'
  })
  return result
}

const getUserinfo = async ({ userId, username }) => {
  const whereOption = {}
  userId && Object.assign(whereOption, { id: userId })
  username && Object.assign(whereOption, { username })

  const result = await User.findOne({
    attributes: ['id', 'username', 'password', 'isAdmin'],
    where: whereOption,
  })

  return result
}

const _updateUserById = async (userId, { username, password, isAdmin }) => {
  const whereOption = { id: userId }
  const newUser = {}

  username && Object.assign(newUser, { username })
  password && Object.assign(newUser, { password })
  isAdmin ?? Object.assign(newUser, { isAdmin: isAdmin })

  const result = await User.update(newUser, { where: whereOption })
  return result
}

const resetPasswordById = (userId, password) => {
  return _updateUserById(userId, { password })
}

const resetAuthById = (userId, isAdmin) => {
  return _updateUserById(userId, { isAdmin })
}

module.exports = {
  createUser,
  getUserinfo,
  resetPasswordById,
  resetAuthById
}